package com.yhgarden.bbs.controller.common;

import com.yhgarden.bbs.entity.common.Adjunct;
import com.yhgarden.bbs.model.response.BaseResponse;
import com.yhgarden.bbs.service.api.common.AdjunctService;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = {"/common/adjunct","*/common/adjunct"})
public class AdjunctController {

    @Autowired
    private AdjunctService adjunctService;

    /**
     * 文件上传
     * @param importFiles
     * @param request
     * @return
     */
    @RequestMapping(value = {"/fileUpload"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse fileUpload(@RequestParam("files") MultipartFile[] importFiles, HttpServletRequest request) throws IOException {
        BaseResponse res = adjunctService.fileUpload(importFiles, request);
        return res;
    }


    /**
     * ckeditor编辑器专用文件上传接口
     * @param importFiles
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = {"/ckeditor/fileUpload"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> ckEditorFileUpload(@RequestParam("upload") MultipartFile[] importFiles, HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        StringBuffer url = request.getRequestURL();
        Map<String,Object> message = new HashMap<>();
        //获得上传后的文件信息
        try{
            MultipartFile importFile = importFiles[0];
            float size = importFile.getSize() == 0 ? 0 : importFile.getSize() / 1024;
            String fileFileName = importFile.getOriginalFilename();
            String prefix = fileFileName.substring(fileFileName.lastIndexOf(".")+1);
            //判断是否为图片，图片不能大于1M
            if(ThumbnailatorUtils.isSupportedOutputFormat(prefix)){
                if(size >= 1024){
                    result.put("uploaded",0);
                    message.put("message", "图片大小不能超过1M");
                    result.put("error", message);
                    return result;
                }
            }else if(size >= 1024*100){
                result.put("uploaded",0);
                message.put("message", "文件大小不能超过100M");
                result.put("error", message);
                return result;
            }
            BaseResponse res = adjunctService.fileUpload(importFiles, request);
            List<Adjunct> adjunctList = (List<Adjunct>) res.getData();
            //文件id
            String fileId = adjunctList.get(0).getId();
            String fileName = adjunctList.get(0).getTitle();
            //文件下载接口,拼接完整的路由
//            String filePath = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
            String filePath = "/common/adjunct/fileDownload/"+fileId;
            result.put("uploaded",1);
            result.put("fileName",fileName);
            result.put("url",filePath);
        }catch (Exception e){
            result.put("uploaded",0);
            message.put("message",e.getMessage());
            result.put("error",message);
        }
//        System.out.println(result.toString());
        return result;
    }


    /**
     * 根据url获取图片到服务器
     * @return
     * @throws IOException
     */
    @RequestMapping(value = {"/getImageByUrl"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse getImageByUrl(@RequestBody Map<String,Object> parameters) throws IOException {
        String imageurl = parameters.get("imageurl").toString();
        String name = parameters.get("name").toString();
        BaseResponse response = adjunctService.getImageByUrl(imageurl, name);
        return response;
    }

    /**
     * 文件下载通用接口
     *
     * @param response
     * @param adjunctId 文件id
     */
    @RequestMapping(value = {"/fileDownload/{adjunctId}","/thumbnail/fileDownload/{widthHeight}/{adjunctId}"}, method = RequestMethod.GET)
    public void fileDownload(HttpServletResponse response,
                                     @PathVariable("adjunctId") String adjunctId,
                                     @PathVariable(value = "widthHeight",required = false) String widthHeight) throws IOException {
        Date date = new Date();
        response.setDateHeader("Last-Modified",date.getTime()); //Last-Modified:页面的最后生成时间
        response.setDateHeader("Expires",date.getTime()+1*60*60*1000); //Expires:过时期限值
        response.setHeader("Cache-Control", "public"); //Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
        response.setHeader("Pragma", "Pragma"); //Pragma:设置页面是否缓存，为Pragma则缓存，no-cache则不缓存
        BaseResponse res = adjunctService.fileDownload(response, adjunctId, widthHeight);
    }

    /**
     * 文件断点下载通用接口（兼容ios系统播放视频，需要使用该接口）
     *
     * @param request
     * @param response
     * @param adjunctId
     * @throws IOException
     */
    @RequestMapping(value = "/fileRangeDownload/{adjunctId}", method = RequestMethod.GET)
    public void fileRangeDownload(HttpServletRequest request,HttpServletResponse response, @PathVariable("adjunctId") String adjunctId) throws IOException {
        Date date = new Date();
        response.setDateHeader("Last-Modified",date.getTime()); //Last-Modified:页面的最后生成时间
        response.setDateHeader("Expires",date.getTime()+1*60*60*1000); //Expires:过时期限值
        response.setHeader("Cache-Control", "public"); //Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
        response.setHeader("Pragma", "Pragma"); //Pragma:设置页面是否缓存，为Pragma则缓存，no-cache则不缓存
        BaseResponse res = adjunctService.fileRangeDownload(request,response, adjunctId);
    }


    /**
     * 文件打包下载
     * @param request
     * @param response
     * @param adjunctIds
     * @throws IOException
     */
    @RequestMapping(value = "/fileBatchDownload/{adjunctIds}", method = RequestMethod.GET)
    public void fileBatchDownload(HttpServletRequest request,HttpServletResponse response, @PathVariable("adjunctIds") String adjunctIds) throws Exception {
        Date date = new Date();
        response.setDateHeader("Last-Modified",date.getTime()); //Last-Modified:页面的最后生成时间
        response.setDateHeader("Expires",date.getTime()+1*60*60*1000); //Expires:过时期限值
        response.setHeader("Cache-Control", "public"); //Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
        response.setHeader("Pragma", "Pragma"); //Pragma:设置页面是否缓存，为Pragma则缓存，no-cache则不缓存
        BaseResponse res = adjunctService.fileBatchDownload(request,response,adjunctIds);
    }

}
